/**
 * 编辑病例页面
 */

import React, {Component} from 'react';
import {
  View,
  TextInput,
  Text,
  StyleSheet,
  Dimensions,
  Button,
  Image,
  ScrollView,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import DatePicker from 'react-native-datepicker';
import Line from '../components/Line';
import ImagePicker from 'react-native-image-crop-picker';
import {createDiseaseHistory} from '../../api/mine';
import {loadingClose, loadingOpen, setToastMsg} from '../../actions/index';
import {getStorage} from '../../storage';
import {connect} from 'react-redux';
import {SERVER_BASE} from '../../util/fetch';

const {width} = Dimensions.get('window');

class AddCase extends Component {
  constructor(props) {
    super(props);
    let date = new Date();
    let string =
      date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
    this.state = {
      img1: '',
      img2: '',
      img3: '',
      img4: '',
      img5: '',
      imgCount: 0,
      pictures: [],
      picturesTemp: [],
      title: '',
      hospital: '1',
      disease: '1',
      description: '1',
      date: '1998-10-02',
      maxDate: string,
    };
    console.log(string);
  }

  /**
   * 选择照片，最多照片数量为八个
   *  将图片的地址放在数组中，最后存在state中
   *
   *  做的比较简单，图片只能一次选择，再次选择从新开始
   */
  selectPic() {
    ImagePicker.openPicker({multiple: true, mediaType: 'photo'}).then(
      images => {
        // let list = this.state.pictures;
        // let tempList = this.state.picturesTemp;
        let list = [];
        let tempList = [];
        //校验图片
        if (images.length > 3) {
          alert('图片数量超出限制！');
        } else {
          images.map(item => {
            if (item.size < 5 * 1024 * 1024) {
              list.push(item.path);
              tempList.push(item.path);
              this.setState({imgCount: ++this.state.imgCount});
              console.log(item.path);
            } else {
              this.setState({imgCount: 0});
              list = [];
              tempList = [];
              alert('图片大小超限制！');
              return;
            }
          });
          this.setState({
            pictures: list,
            picturesTemp: tempList,
          });
        }
      },
    );
  }
  async submit() {
    let data = this.state.pictures;
    console.log('data', data);
    let _pictures = [];

    // data.map(item => {
    //   console.log(item);
    //   item = item.toString();
    //   let temp = {
    //     uri: item,
    //     type: 'multipart/form-data',
    //     name: item.substr(item.lastIndexOf('/') + 1),
    //   };
    //   _pictures.push(temp);
    //   this.setState({
    //     pictures: _pictures,
    //   });
    // });

    //准备回调的参数
    let _data = {};
    _data.title = this.state.title;
    _data.hospital = this.state.hospital;
    _data.disease = this.state.disease;
    _data.description = this.state.description;
    _data.time = this.state.date;
    _data.pictures = data;

    let formData = new FormData();
    for (let i = 0; i < data.length; i++) {
      let file = {
        uri: data[i],
        type: 'multipart/form-data',
        name: data[i].substr(data[i].lastIndexOf('/') + 1),
      };
      // _pictures.push(file);
      formData.append('pictures', file);
    }
    // let param = {
    //   title: this.state.title,
    //   hospital: this.state.hospital,
    //   disease: this.state.disease,
    //   pictures: _pictures,
    //   description: this.state.description,
    //   time: this.state.year + '-' + this.state.month + '-' + this.state.day,
    // };
    formData.append('title', this.state.title);
    formData.append('hospital', this.state.hospital);
    formData.append('disease', this.state.disease);
    // formData.append('pictures', _pictures);
    formData.append('description', this.state.description);
    formData.append('time', this.state.date);
    // console.log('param', param);
    let token = await getStorage('token');
    this.props.loadingOpen();
    fetch(SERVER_BASE + '/api/user/createDiseaseHistory.shtml', {
      method: 'post',
      headers: {
        imei: '1',
        version: '2',
        token: token,
      },
      body: formData,
    })
      .then(response => {
        // console.log(response.text());
        return response.json();
      })
      .then(responseJson => {
        this.props.loadingClose();
        if (responseJson.error_code === 0 || responseJson.error_code === '0') {
          this.props.setToastMsg('上传成功');
          this.props.navigation.getParam('callback')(_data);
          this.props.navigation.goBack();
        } else {
          this.props.setToastMsg('上传失败');
        }
      })
      .catch(e => {
        console.log(e);
        this.props.loadingClose();
        this.props.setToastMsg('上传失败');
      });
    // console.log(token);
    // let result = await createDiseaseHistory(param);
  }

  /**
   * 渲染图片的函数，将数组中的个个元素（图片路径）
   * 渲染到Image标签中
   * 最后的添加图片的地址是在基础数组中添加一个新元素，放在了新数组里面，state的pictures数组里面没有
   */
  renderPic(item) {
    // alert(this.state.pictures.indexOf(item));
    if (this.state.pictures.indexOf(item) === -1) {
      // alert(1);
      return (
        <TouchableOpacity
          style={{width: 100, height: 100}}
          onPress={() => {
            this.selectPic();
          }}>
          <Image source={{uri: item}} style={{width: 100, height: 100}} />
        </TouchableOpacity>
      );
    }
    // alert(2);
    return (
      <TouchableOpacity
        style={{width: 100, height: 100}}
        onPress={() => this.removePic(item)}>
        <Image source={{uri: item}} style={{width: 100, height: 100}} />
      </TouchableOpacity>
    );
  }
  /**
   * 删除一张照片，删除数组中的元素，调用setState方法，会重新调用render函数
   */
  removePic(picPath) {
    let pic = this.state.pictures;
    let picTemp = this.state.picturesTemp;
    pic.splice(pic.findIndex(item => item === picPath), 1);
    picTemp.splice(picTemp.findIndex(item => item === picPath), 1);
    this.setState({
      pictures: pic,
      picturesTemp: picTemp,
      imgCount: this.state.pictures.length,
    });
  }

  updateDate(date) {
    this.setState({date: date});
    let arr = date.split('-');
    this.setState({
      year: arr[0],
      month: arr[1],
      day: arr[2],
    });
  }
  /**
   * 渲染函数，在渲染开始前，将添加照片按钮的照片放到一个新数组中
   *    并且用这个数组来解析
   */
  render() {
    let data = this.state.picturesTemp;
    let addUrl = 'https://hgbc-1.oss-cn-beijing.aliyuncs.com/test/increase.png';
    if (data.indexOf(addUrl) === -1) {
      data.push(addUrl);
    }
    // alert(data[0]);
    return (
      <ScrollView>
        <Text style={styles.keyFont}>标题</Text>
        <Line />
        <TextInput
          placeholder={'输入标题'}
          style={styles.textInput}
          onChangeText={text => this.setState({title: text})}
        />
        <Text style={styles.keyFont}>时间</Text>
        <View style={styles.dateContainer}>
          <TextInput
            style={[styles.textInput, {width: 80}]}
            editable={false}
            value={this.state.year}
          />
          <Text style={[styles.keyFont, {marginTop: 17, marginLeft: 5}]}>
            年
          </Text>
          <TextInput
            style={[styles.textInput, {width: 50, marginLeft: 10}]}
            editable={false}
            value={this.state.month}
          />
          <Text style={[styles.keyFont, {marginTop: 17, marginLeft: 5}]}>
            月
          </Text>
          <TextInput
            style={[styles.textInput, {width: 50, marginLeft: 10}]}
            editable={false}
            value={this.state.day}
          />
          <Text style={[styles.keyFont, {marginTop: 17, marginLeft: 5}]}>
            日
          </Text>
          <DatePicker
            style={{paddingRight: 20}}
            date={this.state.maxDate}
            mode="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            //minDate="2016-05-01"
            maxDate={this.state.maxDate}
            confirmBtnText="Confirm"
            cancelBtnText="Cancel"
            hideText={true}
            customStyles={{
              dateIcon: {
                left: 0,
                top: 4,
                marginLeft: 0,
              },
              // dateInput: {
              //   //marginLeft: 36,
              //   border: 2,
              // },
              dateInput: {
                width: 0,
              },
              // ... You can check the source to find the other keys.
            }}
            onDateChange={date => {
              this.updateDate(date);
            }}
          />
        </View>

        <Text style={styles.keyFont}>医疗单位</Text>
        <Line />
        <TextInput
          placeholder={'去了哪个医院呢？'}
          style={styles.textInput}
          onChangeText={text => this.setState({hospital: text})}
        />
        <Text style={styles.keyFont}>病症</Text>
        <Line />
        <TextInput
          placeholder={'这里填没病，当然是最好了'}
          style={styles.textInput}
          onChangeText={text => this.setState({disease: text})}
        />
        <Text style={styles.keyFont}>病例描述</Text>
        <Line />
        <TextInput
          multiline={true}
          placeholder={'输入对此次病例的描述吧！'}
          style={styles.textInput}
          onChangeText={text => this.setState({description: text})}
        />
        <Text style={styles.keyFont}>
          添加图片 {'  '}
          {this.state.imgCount} / 3
        </Text>
        <View style={styles.imgContainer}>
          <FlatList
            data={data}
            renderItem={({item}) => this.renderPic(item)}
            keyExtractor={index => index}
            numColumns={3}
          />
        </View>
        <View
          style={{
            width: width - 40,
            marginLeft: 20,
            marginTop: 10,
            marginBottom: 50,
          }}>
          <Button
            title={'完 成'}
            onPress={() => {
              this.submit();
            }}
          />
        </View>
      </ScrollView>
    );
  }
}
export default connect(
  null,
  dispatch => ({
    loadingOpen: () => dispatch(loadingOpen()),
    loadingClose: () => dispatch(loadingClose()),
    setToastMsg: text => dispatch(setToastMsg(text)),
  }),
)(AddCase);
const styles = StyleSheet.create({
  container: {},
  keyFont: {
    marginTop: 5,
    marginLeft: 20,
    color: '#00AEFF',
    fontSize: 16,
  },
  textInput: {
    marginTop: 8,
    marginLeft: 20,
    width: 375 - 40,
    backgroundColor: '#F8F6F9',
    height: 40,
  },
  dateContainer: {
    flexDirection: 'row',
    marginTop: 5,
  },
  imgContainer: {
    marginLeft: 20,
    width: 375 - 40,
  },
  img: {
    width: 100,
    height: 100,
    backgroundColor: '#F8F8F8',
  },
  imgX: {
    width: 100,
    height: 100,
  },
});
